import api from '@api'

const state = {
  list: {
    data: [],
    state: -1,
    pageNum: 0,
    page:1
  },
  availNum: 0,
  noavailNum: 0
}

const getters = {
  ['getCoupon'] (state) {
    return state.list
  }
}

const actions = {
  async ['getCoupon'] ({commit,state}, {page, couponState}) {
    if(state.list.state !=  couponState) {
      commit('clearCoupon');
    }
    let config = {
      eState: couponState,
      CurrentPage: page,
      PageSize: 5
    }
    let {data: {couponList, availNum, noavailNum, pageNum, StatusCode}} = await api.get('api/v1/userInfo/userCouponList.ashx', config);
    if(StatusCode === '200'){
      commit('setCoupon', {
        couponList,
        pageNum: Number(pageNum),
        page,
        couponState
      });
      commit('setAvail', availNum)
      commit('setNoAvail', noavailNum)
    }
    return StatusCode;
  }
}

const mutations = {
  ['setCoupon'] (state, {couponList, pageNum, page, couponState}) {
    state.list.data = page == 1? couponList : state.list.data.concat(couponList);
    state.list.pageNum = pageNum;
    state.list.state =  couponState;
    state.list.page = page;
  },
  ['setAvail'] (state, avail) {
    state.availNum = avail
  },
  ['setNoAvail'] (state, noavail) {
    state.noavailNum = noavail
  },
  ['clearCoupon'] (state) {
    state.list = {
      data: [],
      state: -1,
      pageNum: 0,
      page:1
    }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}